import React from 'react'
import { Table,Icon,Modal,Popconfirm,Message,Form,Row,Select,Col,Radio,Button,Input,DatePicker} from 'antd';
const FormItem = Form.Item;
import api from '../../../api/advexam';
import PanelBox from '../../../components/PanelBox';
import AdvExam from '../../Form/AdvExam';
import moment from 'moment';
const { RangePicker } = DatePicker;
const RadioGroup = Radio.Group;

export default class TablePage extends React.Component {
  columns = [{
    title: '广告标题',
    key: 'title',
    dataIndex: 'title',
    width: '13%',
  },{
    title: '广告内容',
    key: 'content',
    dataIndex: 'content',
    width: '13%',
  },  {
    title: '处理时间',
    key: 'dealDate',
    sorter: false,
    dataIndex: 'dealDate',
    width: '14%',
  }, {
    title: '是否系统广告',
    dataIndex: 'isSystem',
    render:(text, record, index) =>  {
      switch(record.isSystem){
        case 1:
          return '是';
        case 0:
          return '否';
        default:
          return '未知';
      }
    },
  },{
    title: '状态',
    dataIndex: 'state',
    render:(text, record, index) =>  {
        switch(record.state){
          case 1:
            return '待审核';
          case 3:
            return '拒绝';
          case 2:
            return '通过';
          default:
            return '未知';
        }
      },
  } ,  {
    title: '广告类型',
    dataIndex: 'type',
    render:(text, record, index) =>  {
        switch(record.type){
          case 1:
            return '手机屏保广告';
          case 2:
            return '手机分类广告';
          case 3:
            return '广告机广告';
          case 4:
            return '家庭锁广告';
          default:
            return '未知';
        }
      },
  } ,{
    title: '操作',
    key: 'id',
    dataIndex: 'id',
    render: (text, record) => (
      <span>
        { record.state == 1 ?
        <a href="javascript:void(0)" onClick={this.startCreateUser_default.bind(this,record)}>审核</a>
        : ''}

          { record.state == 3 ?
        <a href="javascript:void(0)">已拒绝</a>
        : ''}

          { record.state == 2 ?
        <a href="javascript:void(0)">已通过</a>
        : ''}

        <span className="ant-divider" />
        <a href="javascript:void(0)"  onClick={this.startUpdateUser.bind(this,record)} >详情</a>
        <span className="ant-divider" />
        <Popconfirm title="您是否要删除该广告?" onConfirm={this.delete.bind(this,record.id)} okText="是" cancelText="否">
          <a href="javascript:void(0)">删除</a>
        </Popconfirm>
      </span>
    ),
  }];

  state = { 
    data: [],
    listtype: [],
    child:[],
    pagination: {},
    loading: false,
    isOpenCreateUser: false,
    isOpenEditUser: false,
    offices:null,
    area:null,
    defaulTitle:null
  };
  handleTableChange = (pagination, filters, sorter) => {
    const pager = this.state.pagination;
    if(pagination.size==1){
      pager.current = pagination.current!=null?pagination.current:pagination.pageNum-1;
    }else{
      pager.current = pagination.current!=null?pagination.current:pagination.pageNum;
    }
    this.setState({
      pagination: pager,
    });
    this.fetch({
      pageSize: pagination.pageSize,  //每页现实条数
      pageNum: pagination.current,  //当前页数
      sortField: sorter.field,
      sortOrder: sorter.order,
      ...filters, 
    });
  }

   rowSelection = {
    onChange: (selectedRowKeys, selectedRows) => {
      //console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
      this.setState({
        delIds: `${selectedRowKeys}`,
      });
    },
    getCheckboxProps: record => ({
      disabled: record.name === 'Disabled User', // Column configuration not to be checked
    }),
  };


  

  fetch = (params = {}) => {

    this.setState({ loading: true });
    if(params.title!=''){
      this.defaulTitle=params.title;
    }
    api.get('/queryAll', {   //分业查询所有
      ...params,
      responseType: 'json'
    }).then((data) => {
      data = data.data;
      const pagination = data;
      pagination.total = data.pages*data.pageSize;
      this.setState({
        loading: false,
        data: data.list,
        pagination,
      });
    });
  } 
  
   componentDidMount = () =>{
    this.fetch({
      pageSize: 20,
      pageNum: 1
    });
  }

  startCreateUser_default = (record) =>{
     this.clear;
    this.setState({
      isOpenCreateUser: true,
      hardinfo:record,
    });
  }
  
  closeCreateUser = () =>{
    this.setState({
      isOpenCreateUser: false,
    });
  }
  closeaddDict = () =>{
    this.setState({
      isOpenCreateUser: false,
    });
    this.handleTableChange(this.state.pagination,{},{});
  }
  startUpdateUser = (record) =>{
    console.log(record);
    if (this.resetFields) this.resetFields();
      this.setState({
        isOpenEditUser: true,
        hardinfo:record,
      });
  }
  closeUpdateUser = () =>{
    this.setState({
      isOpenEditUser: false,
    });
  }
  closeupdateDict = () =>{
    this.setState({
      isOpenEditUser: false,
    });
    this.handleTableChange(this.state.pagination,{},{});
  }


  //单个删除
  delete = (id,event) => {
    this.deleteHard(id);
  }


  //多删除
  deleteAll = () => {
    const ids = this.state.delIds;
    if(ids == '' || ids == null){
      Message.error('请选择你要删除的广告机！');
      return;
    }
    this.deleteHard(ids);
   }


   deleteHard = (ids) => {
    api.delete('/deleteAdvExam', {ids:ids}).then((data) => {
      const result= data.data;
     if(result.code == 0){
      Message.success('删除成功！');
      this.fetch();
     }else{
      Message.error(result.message);
     }
    });
  }

   
 // 接收子组件传入的数据及其方法
 initChildrenParams = (params) => {
  this.resetFields = params.resetFields;
}



  render() {
    let _this = this;
    let timeDef="";
    const formItemLayout = {
      labelCol: { span: 6 },
      wrapperCol: { span: 16 },
    };
    class CustomizedForm extends React.Component {
      // 开始搜索
      goSearch = (e) => {
        e.preventDefault();
        this.props.form.validateFieldsAndScroll((err, values) => {   //提交后得到from表单中得值
          if (!err) {
            let params = this.props.form.getFieldsValue().search;
             params.pageSize=20;
             params.pageNum=1;
             _this.fetch(params);
          }
        });
        return false;
      }

      render() {
        const { getFieldDecorator} = this.props.form;
        const search = {
          name: "title",
        };
        return <Form onSubmit={this.goSearch} layout="inline" style={{marginBottom:'10px'}}>
          <FormItem {...formItemLayout} label="广告标题" style={{marginRight:'-25px'}}>
            {getFieldDecorator('search.title', {
              initialValue:_this.defaulTitle ? _this.defaulTitle: ''
            })(
              <Input type="text" placeholder="请输入广告标题"/>
            )}
          </FormItem>
         {/*  <FormItem {...formItemLayout} label="添加日期" style={{marginRight:'-20px'}}>
            {getFieldDecorator('search.date', {
                initialValue:timeDef
            })(
              <RangePicker format="YYYY/MM/DD" />
            )}
          </FormItem> */}
          <FormItem style={{marginLeft:'10px'}}>
            <Button type="primary" icon="search" htmlType="submit">搜索</Button>
          </FormItem>
          <FormItem>
              <Button type="primary" icon="minus">
              <Popconfirm title="您是否要删除选中的所有广告?" onConfirm={_this.deleteAll} okText="是" cancelText="否">删除所选
              </Popconfirm>  
              </Button>
            
          </FormItem>
          {/* <FormItem style={{marginRight:'10px'}}>
            <Button type="primary" icon="plus" onClick={_this.startCreateUser_default}>新建门闸机</Button>
          </FormItem> */}
        </Form>
      }
    }
    const CusForm = Form.create({})(CustomizedForm);


    class ManageForm extends React.Component {
      state = {
        loading: false
      };
      submit = (e) => {
        e.preventDefault();
        this.props.form.validateFieldsAndScroll((err, values) => {
          if (!err) {
            this.setState({
              loading: true
            });
            api.put('/updateAdvExam', values).then((res) => {
              const result = res.data;
              const {determine} = this.props;
              if (result.code == 0) {
                Message.success('提交成功！');
                determine();
              } else {
                Message.error(result.message);
              }
              this.setState({
                loading: false
              });
            }).catch(e => {
              console.error(e);
              Message.error("提交失败");
              this.setState({
                loading: false
              });
            });
          }
        });
      }
    
      clear = () => {
        this.props.form.resetFields();
      }

      //关闭
      closePopup = () =>{
        this.setState({
          isOpenCreateUser: false,
        });
        this.handleTableChange(this.state.pagination,{},{});
      }
    
      render() {
        const { getFieldDecorator, resetFields} = this.props.form;
        const hardinfo = this.props.hardinfo;
        const {close,callbackParent} = this.props;
        const formItemLayout = {
          labelCol: { span: 6 },
          wrapperCol: { span: 14 },
        };
         // 把重置表单的方法传给父亲
        callbackParent({
          resetFields:resetFields
        });
    
        const tailFormItemLayout = {
          wrapperCol: {
            xs: {
              span: 14,
              offset: 0,
            },
            sm: {
              span: 14,
              offset: 6,
            },
          },
        };
    
        return (
          <Form className="passowrd-form" layout="horizontal" onSubmit={this.submit}>
            {getFieldDecorator('id', {
              initialValue: hardinfo.id
            })(
              <Input type="hidden" />
              )}
        <FormItem
          {...formItemLayout}
          label="状态"
          hasFeedback
        >
          {getFieldDecorator('state', {
            rules: [{
            }],
            initialValue:'3'
          })(
            <RadioGroup name="state">
            {/*   <Radio value={'1'}>待审核</Radio> */}
              <Radio value={'3'}>拒绝</Radio>
              <Radio value={'2'}>通过</Radio>
            </RadioGroup>
          )}
        </FormItem>
        <FormItem
          {...formItemLayout}
          label="描述"
          hasFeedback
        >
          {getFieldDecorator('remarks ', {
            rules: [{
              required: true, message: '描述!',
            }],
            initialValue:'描述'
          })(
            <textarea style={{width:'300',height:'60'}}></textarea>
          )}
        </FormItem>
            <FormItem {...tailFormItemLayout}>
              <Button loading={this.state.loading} type="primary" htmlType="submit" size="large" style={{ marginRight: '10px' }}>提交</Button>
              <Button onClick={close}>关闭</Button>
            </FormItem>
          </Form>
        );
      }
    }
    
    const ExamineForm = Form.create()(ManageForm);

    return (
      <div>
        <CusForm/>
        <PanelBox>
          <Table columns={this.columns}
            rowKey={record => record.id}
            dataSource={this.state.data}
            pagination={this.state.pagination}
            loading={this.state.loading}
            onChange={this.handleTableChange}
            expandedRowRender={record => <p style={{ margin: 0 }}>创建时间:{record.createDate}　　　备注:{record.remarks}</p>}
            rowSelection={this.rowSelection}
          />
        </PanelBox>
        <Modal
          title="审核"
          visible={this.state.isOpenCreateUser}
          onOk={this.closeCreateUser}
          onCancel={this.closeCreateUser}
          wrapClassName="vertical-center-modal"
          width="500"
          footer={null}
        >
          <ExamineForm close={this.closeCreateUser} determine={this.closeaddDict} hardinfo={this.state.hardinfo}  callbackParent={this.initChildrenParams} />
        </Modal>
        <Modal
          title="审核信息详情"
          visible={this.state.isOpenEditUser}
          onOk={this.closeUpdateUser}
          onCancel={this.closeUpdateUser}
          wrapClassName="vertical-center-modal"
          width="1000"
          footer={null}
        >
          <AdvExam upfinish={this.closeupdateDict} close={this.closeUpdateUser} area={this.state.area}  offices={this.state.offices}  hardinfo={this.state.hardinfo} callbackParent={this.initChildrenParams}/>
        </Modal>
      </div>
    );
  }
}
